import React, { useEffect, useState } from 'react';
//closure:闭包
//闭包陷阱可以用useEffect依赖num,来获取最新的值
const Closure: React.FC = () => {
  const [num, setNum] = useState(0);
  const handle = () => {
    setNum((num) => num + 1);
    setTimeout(() => {
      console.log(num); //根据作用域链找num变量,上一次作用域中num值为0
    }, 2000);
  };
  useEffect(() => {
    console.log(num); //可以获取到最新的值
  }, [num]);
  return (
    <>
      <div className="closure">
        <div>{num}</div>
        <button onClick={handle}>新增</button>
      </div>
    </>
  );
};
export default Closure;
